package com.hbu.fleastreet.controller.frontend;

import com.hbu.fleastreet.common.Constant;
import com.hbu.fleastreet.entity.Result;
import com.hbu.fleastreet.entity.ResultCode;
import com.hbu.fleastreet.entity.User;
import com.hbu.fleastreet.exception.LoginException;
import com.hbu.fleastreet.services.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import static com.hbu.fleastreet.common.Constant.NAME_PREFIX;

/**
 * 前端用户管理
 */
@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private IUserService userService;

	/**
	 * 打开登录页面
	 * @return
	 */
	@GetMapping("/login")
	public String toLogin() {
		return "/frontend/account";
	}

	/**
	 * 登录
	 *
	 * @param username
	 * @param password
	 */
	@PostMapping("/login")
	public void login(String username,
			String password,
			HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		//登录成功 重定向到首页
		User user = userService.checkLogin(username, password);
		if (user != null) {
			//登录成功 重定向到首页
			request.getSession().setAttribute("user", user);
			List<Integer> productIds = (List<Integer>) request.getSession()
					.getAttribute(Constant.NAME_PREFIX + Constant.NO_LOGIN_USER_ID);
			if (productIds != null && productIds.size() > 0) {
				request.getSession().setAttribute(Constant.NAME_PREFIX + user.getUserId(), productIds);
				request.getSession().removeAttribute(Constant.NAME_PREFIX + Constant.NO_LOGIN_USER_ID);
			}
			response.sendRedirect("/fleastreet/index");
		} else {
			throw new LoginException("登录失败！ 用户名或者密码错误");
		}

	}

	/**
	 * 打开注册页面
	 *
	 * @return
	 */
	@GetMapping("/register")
	public String toRegister() {
		return "/frontend/register";
	}

	/**
	 * 注册
	 * 根据选择是否直接登陆决定跳转到首页，或者到登陆页
	 */
	@PostMapping("/register/{type}")
	@ResponseBody
	public Result<Boolean> register(String userName,
			String password,
			String email, @PathVariable("type") Integer type, HttpServletRequest request,
			HttpServletResponse response) {
		User user = new User();
		user.setUserName(userName);
		user.setPassword(password);
		user.setEmail(email);
		user.setState(Constant.STATE_1000);
		try {
			userService.saveUser(user);
			if (type == 1) {
				User user1 = userService.checkLogin(userName, password);
				request.getSession().setAttribute("user", user1);
				List<Integer> productIds = (List<Integer>) request.getSession()
						.getAttribute(Constant.NAME_PREFIX + Constant.NO_LOGIN_USER_ID);
				if (productIds != null && productIds.size() > 0) {
					request.getSession().setAttribute(Constant.NAME_PREFIX + user1.getUserId(), productIds);
					request.getSession().removeAttribute(Constant.NAME_PREFIX + Constant.NO_LOGIN_USER_ID);
				}
			}
		} catch (Exception e) {
			return new Result<>(ResultCode.ERROR, e.getMessage());
		}
		return new Result<Boolean>(ResultCode.SUCCESS, true);
	}

	/**
	 * 登出
	 */
	@GetMapping("/logout")
	public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		User user = (User) request.getSession().getAttribute("user");
		if (user != null) {
			List<Integer> productIds = (List<Integer>) request.getSession()
					.getAttribute(Constant.NAME_PREFIX + user.getUserId());
			if (productIds != null && productIds.size() > 0) {
				request.getSession().setAttribute(Constant.NAME_PREFIX + Constant.NO_LOGIN_USER_ID, productIds);
				request.getSession().removeAttribute(NAME_PREFIX + user.getUserId());
			}
		}
		request.getSession().removeAttribute("user");
		response.sendRedirect("/fleastreet/index");
	}

	/**
	 * 验证用户名是否唯一
	 * @param userName
	 * @return
	 */
	@ResponseBody
	@GetMapping("/checkUserName/{userName}")
	public Result<Boolean> checkUserName(@PathVariable("userName") String userName) {
		List<User> users = userService.checkUserName(userName);
		if (users == null || users.isEmpty()) {
			return new Result<>(ResultCode.SUCCESS, true);
		}
		return new Result<>(ResultCode.SUCCESS, false);
	}

}
